package com.jcfk.eam.service.equ;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.equ.EfaLiabilityExtentDao;
import com.jcfk.eam.domain.dto.equ.EfaLiabilityExtentDTO;
import com.jcfk.eam.domain.dto.equ.EfaLiabilityExtentEquipDTO;
import com.jcfk.eam.domain.dto.equ.EfaLiabilityExtentPersonDTO;
import com.jcfk.eam.domain.po.equ.EfaLiabilityExtent;
import com.jcfk.eam.domain.po.equ.EfaLiabilityExtentEquip;
import com.jcfk.eam.domain.po.equ.EfaLiabilityExtentPerson;
import com.jcfk.eam.domain.query.equ.EfaLiabilityExtentQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 设备责任范围
 *
 * @author yrl
 * @email
 * @date 2025-04-22
 */
@Service
public class EfaLiabilityExtentService extends BaseService<EfaLiabilityExtentDao, EfaLiabilityExtent> {


    @Autowired
    private EfaLiabilityExtentEquipService efaLiabilityExtentEquipService;
    @Autowired
    private EfaLiabilityExtentPersonService efaLiabilityExtentPersonService;

    /**
     * EfaLiabilityExtent分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EfaLiabilityExtentDTO> queryByPage(DataPage<EfaLiabilityExtentDTO> page, EfaLiabilityExtentQuery query) {
        // 分页查询
        query.setLiabilityExtent(StringUtils.isEmpty(query.getLiabilityExtent()) ? query.getLiabilityExtent() : query.getLiabilityExtent() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EfaLiabilityExtentDTO>
     */
    public List<EfaLiabilityExtentDTO> getList(EfaLiabilityExtentQuery query) {
        // 查询条件
        QueryWrapper<EfaLiabilityExtent> qw = new QueryWrapper<>();
        qw.lambda().like(!StrUtil.isEmpty(query.getLiabilityExtent()), EfaLiabilityExtent::getLiabilityExtent, query.getLiabilityExtent());
        qw.lambda().eq(query.getDeleted() != null, EfaLiabilityExtent::getDeleted, query.getDeleted());
        qw.lambda().eq(query.getDeleted() == null, EfaLiabilityExtent::getDeleted, 0);
        // 查询数据
        List<EfaLiabilityExtent> list = super.list(qw);

        return convertList(list, EfaLiabilityExtentDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<EfaLiabilityExtentDTO>
     */
    public List<EfaLiabilityExtentEquipDTO> getDetails(EfaLiabilityExtentQuery query) {
        // 查询条件
        QueryWrapper<EfaLiabilityExtentEquip> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), EfaLiabilityExtentEquip::getLiabilityExtentId, query.getId());

        // 查询数据
        List<EfaLiabilityExtentEquip> list = efaLiabilityExtentEquipService.list(qw);

        return convertList(list, EfaLiabilityExtentEquipDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<EfaLiabilityExtentDTO>
     */
    public List<EfaLiabilityExtentPersonDTO> getPersons(EfaLiabilityExtentQuery query) {
        // 查询条件
        QueryWrapper<EfaLiabilityExtentPerson> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), EfaLiabilityExtentPerson::getLiabilityExtentId, query.getId());

        // 查询数据
        List<EfaLiabilityExtentPerson> list = efaLiabilityExtentPersonService.list(qw);

        return convertList(list, EfaLiabilityExtentPersonDTO.class);
    }


    /**
     * 判断EfaLiabilityExtent是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EfaLiabilityExtentDTO dto) {
        List<String> equipCodes = dto.getDetails().stream().map(EfaLiabilityExtentEquipDTO::getEquipCode).collect(Collectors.toList());
        List<EfaLiabilityExtentEquipDTO> extentEquips = efaLiabilityExtentEquipService.listByCodes(equipCodes, dto.getType(), dto.getId());
        Assert.isTrue(CollUtil.isEmpty(extentEquips), StrUtil.format( "设备{}已在其他责任范围中存在", extentEquips.stream().map(EfaLiabilityExtentEquipDTO::getEquipCode).collect(Collectors.joining())));
        return RetResult.ok();
    }

    /**
     * 插入设备责任范围
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EfaLiabilityExtentDTO dto) {

        // 保存
        EfaLiabilityExtent item = new EfaLiabilityExtent();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 保存明细表
        efaLiabilityExtentEquipService.saveBatch(dto.getDetails(), item.getId());
        efaLiabilityExtentPersonService.saveBatch(dto.getPersons(), item.getId());
    }


    /**
     * 更新设备责任范围
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EfaLiabilityExtentDTO dto) {

        // 保存
        EfaLiabilityExtent item = new EfaLiabilityExtent();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (EfaLiabilityExtentEquipDTO detail : dto.getDetails()) {
            detail.setLiabilityExtentId(item.getId());
        }
        // 设置关联主键
        for (EfaLiabilityExtentPersonDTO detail : dto.getPersons()) {
            detail.setLiabilityExtentId(item.getId());
        }
        // 保存明细表
        efaLiabilityExtentEquipService.saveBatch(dto.getDetails(), item.getId());
        efaLiabilityExtentPersonService.saveBatch(dto.getPersons(), item.getId());
    }


    /**
     * 根据批量主键删除设备责任范围(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EfaLiabilityExtentDTO dto) {

        EfaLiabilityExtent item = new EfaLiabilityExtent();

        this.setDefaultValue(item);
        item.setDeleted(1);

        QueryWrapper<EfaLiabilityExtent> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());
        efaLiabilityExtentEquipService.update(Wrappers.<EfaLiabilityExtentEquip>lambdaUpdate().eq(EfaLiabilityExtentEquip::getLiabilityExtentId, item.getId()).set(EfaLiabilityExtentEquip::getDeleted, 1));
        efaLiabilityExtentPersonService.update(Wrappers.<EfaLiabilityExtentPerson>lambdaUpdate().eq(EfaLiabilityExtentPerson::getLiabilityExtentId, item.getId()).set(EfaLiabilityExtentPerson::getDeleted, 1));
        return this.update(item, queryWrapper);

    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EfaLiabilityExtent item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }


    /**
     * 根据主键获取设备责任范围信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EfaLiabilityExtentDTO get(String id) {
        // 查询数据
        EfaLiabilityExtent item = this.baseMapper.selectById(id);
        EfaLiabilityExtentDTO dto = new EfaLiabilityExtentDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }


    /**
     * 根据主键获取设备责任范围信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EfaLiabilityExtent item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
        efaLiabilityExtentEquipService.update(Wrappers.<EfaLiabilityExtentEquip>lambdaUpdate().eq(EfaLiabilityExtentEquip::getLiabilityExtentId, item.getId()).set(EfaLiabilityExtentEquip::getDeleted, 1));
        efaLiabilityExtentPersonService.update(Wrappers.<EfaLiabilityExtentPerson>lambdaUpdate().eq(EfaLiabilityExtentPerson::getLiabilityExtentId, item.getId()).set(EfaLiabilityExtentPerson::getDeleted, 1));
    }

    public List<EfaLiabilityExtentPersonDTO> getPersonsByEquipAndType(String equipCode, int type) {
        EfaLiabilityExtentDTO efaLiabilityExtent = this.getByEquipAndType(equipCode, type);
        if (efaLiabilityExtent == null) return ListUtil.empty();
        List<EfaLiabilityExtentPerson> efaLiabilityExtentPersonList = efaLiabilityExtentPersonService.list(Wrappers.<EfaLiabilityExtentPerson>lambdaQuery()
            .eq(EfaLiabilityExtentPerson::getLiabilityExtentId, efaLiabilityExtent.getId())
            .eq(EfaLiabilityExtentPerson::getDeleted, 0));
        return convertList(efaLiabilityExtentPersonList, EfaLiabilityExtentPersonDTO.class);

    }

    private EfaLiabilityExtentDTO getByEquipAndType(String equipCode, int type) {
        return this.baseMapper.getByEquipAndType(equipCode, type);
    }
}

